import os
from minio import Minio
from loguru import logger
from datetime import timedelta


class Client:
    '''
    MinIO客户端封装类，支持上传文件后自动获取URL
    '''

    def __init__(self, endpoint, access_key, secret_key, secure=False):
        self.client = Minio(
            endpoint=endpoint,
            access_key=access_key,
            secret_key=secret_key,
            secure=secure
        )

    def list_buckets(self):
        """列出所有存储桶"""
        return self.client.list_buckets()

    def make_bucket(self, bucket_name):
        """创建存储桶（若不存在）"""
        if not self.client.bucket_exists(bucket_name):
            self.client.make_bucket(bucket_name)
        else:
            logger.warning(f"Bucket {bucket_name} 已存在")

    def upload_file_with_url(self, bucket_name, object_name, file_path, expires=7):
        """
        上传文件并返回访问URL
        - 整合上传和生成链接功能
        - 处理异常并记录日志
        """
        try:
            # 上传文件
            result = self.client.fput_object(
                bucket_name=bucket_name,
                object_name=object_name,
                file_path=file_path
            )
            logger.info(f"文件上传成功: {object_name}")

            # 生成访问URL
            url = self.client.presigned_get_object(
                bucket_name,
                object_name,
                expires=timedelta(days=expires)
            )
            logger.info(f"文件访问URL: {url}")
            return url

        except Exception as e:
            logger.error(f"上传文件 {object_name} 失败: {str(e)}")
            return None

    def get_file_url(self, bucket_name, object_name, expires=7):
        """单独获取已上传文件的URL"""
        try:
            if not self.client.stat_object(bucket_name, object_name):
                logger.error(f"文件 {object_name} 不存在")
                return None

            url = self.client.presigned_get_object(
                bucket_name,
                object_name,
                expires=timedelta(days=expires)
            )
            return url
        except Exception as e:
            logger.error(f"获取URL失败: {str(e)}")
            return None


if __name__ == "__main__":
    image_path = "C:/Users/JUMPIN/Pictures/photo"
    user = Client("192.168.6.16:9005", "S4bPVUF1HdMw4g0fmXbS", "f2YoEaAQGbcGTJ0PZ1DP6u7ENpjNYwnFWliccZyl")

    # 列出存储桶
    logger.info(user.list_buckets())

    # 创建存储桶
    user.make_bucket("data")

    # 上传所有文件并获取URL
    for item in os.listdir(image_path):
        local_path = f"{image_path}/{item}"
        bucket_path = f"test/{item}"

        # 调用整合后的上传+获取URL方法
        url = user.upload_file_with_url(
            "data",
            bucket_path,
            local_path,
            expires=7  # URL有效期7天
        )

        if url:
            logger.info(f"已保存URL: {bucket_path} -> {url}")
        else:
            logger.warning(f"未获取到URL: {bucket_path}")
